import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:provider/provider.dart';

import 'model/resetpwd_entity.dart';
import 'model/set_pwd_entity.dart';

///************************
/// @function 设置密码
/// @创建日期 2019-10-28 11:05:21
///************************
class SetPwd extends StatefulWidget {
  int type = 1;
  String tel;
  String smsCode;

  ///type =1 初始化密码 type==2 找回密码的设置密码

  SetPwd(this.type,this.tel,this.smsCode);

  @override
  _SetPwdState createState() => _SetPwdState();
}

class _SetPwdState extends State<SetPwd> {
  int line1Color = 0xFFe5e5e5;
  int line2Color = 0xFFe5e5e5;

  FocusNode _focusNode1, _focusNode2;
  TextEditingController _t1Controller = TextEditingController();
  TextEditingController _t2Controller = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _focusNode1 = FocusNode();
    _focusNode1.addListener(() {
      if (_focusNode1.hasFocus) {
        print("name 获取到焦点");
        setState(() {
          line1Color = 0xFFdf3033;
          line2Color = 0xFFe5e5e5;
        });
      }
    });
    _focusNode2 = FocusNode();

    _focusNode2.addListener(() {
      if (_focusNode2.hasFocus) {
        print("pwd 获取到焦点");
        setState(() {
          line2Color = 0xFFdf3033;
          line1Color = 0xFFe5e5e5;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          ///x
          getRow1(),

          ///登录
          getRow2(),

          ///输入密码
          getRow4(),
          getLine1(),

          ///输入密码
          getRow5(),
          getLine2(),
          getButton(),
        ],
      ),
    );
  }

  getRow1() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          MediaQueryData.fromWindow(window).padding.top, 0, 0),
      height: ScreenUtil().setWidth(88),
      child: GestureDetector(
        onTap: () {
          Application.router.pop(context);
        },
        child: Image.asset(
          Utils.getImgPath("icon_delete"),
          width: ScreenUtil().setWidth(32),
          height: ScreenUtil().setWidth(32),
        ),
      ),
    );
  }

  getRow2() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(92), ScreenUtil().setWidth(88), 0, 0),
      alignment: Alignment.centerLeft,
      child: Text(
        "设置密码",
        style: TextStyle(
          fontSize: ScreenUtil().setWidth(48),
          color: Colours.appC1,
          fontFamily: Font.PingFangBlod,
        ),
        /*TextStyles.custom(48, Colours.appC1, AppFontFamily.PingFangBlod)*/
      ),
    );
  }

  getRow4() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(90),
          ScreenUtil().setWidth(90), ScreenUtil().setWidth(90), 0),
      child: TextField(
        style:TextStyles.textFiled,
        controller: _t1Controller,
        obscureText: true,
        focusNode: _focusNode1,
        decoration: InputDecoration(
          hintText: "请输入密码",
          hintStyle: TextStyles.custom(
              28, Color(0xFF999999), Font.PingFangMedium),
          border: InputBorder.none,
        ),
      ),
    );
  }

  getRow5() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(90),
          ScreenUtil().setWidth(20), ScreenUtil().setWidth(90), 0),
      child: TextField(
        style:TextStyles.textFiled,
        controller: _t2Controller,
        obscureText: true,
        focusNode: _focusNode2,
        decoration: InputDecoration(
          hintText: "请再次输入",
          hintStyle: TextStyles.custom(
              28, Color(0xFF999999), Font.PingFangMedium),
          border: InputBorder.none,
        ),
      ),
    );
  }

  getLine1() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(90), 0, ScreenUtil().setWidth(90), 0),
      width: ScreenUtil().setWidth(750),
      color: Color(line1Color),
      height: ScreenUtil().setWidth(1),
    );
  }

  getLine2() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(90), 0, ScreenUtil().setWidth(90), 0),
      width: ScreenUtil().setWidth(750),
      color: Color(line2Color),
      height: ScreenUtil().setWidth(1),
    );
  }

  getButton() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(56),
          ScreenUtil().setWidth(96), ScreenUtil().setWidth(56), 0),
      child: UiUtils.bottomBotton("确定", () {
        if (checkPwd()) {
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new LoadingDialog(
                  text: "正在设置密码…",
                );
              });

          if (widget.type == 1) {
            _setPwd();
          } else {
            _rePwd();
          }
        }
      }),
    );
  }

  Future _rePwd() async {
    FormData params = FormData.from(
        {"password": _t1Controller.text, "tel": widget.tel, "smsCode": widget.smsCode});

    DioManager.getInstance().post(Api.RESETPWD, params, (json) {
      print("重置密码:$json");
      ResetpwdEntity entity = ResetpwdEntity.fromJson(json);
      if (entity.code == Api.SUCCESS_CODE) {
        SpUtil.putString(SpKeys.userToken, entity.data.token);
        SpUtil.putString(SpKeys.userPhone, widget.tel);
        Provider.of<UserModel>(context).updateToken(entity.data.token);
        ToastUtil.showShortToast("设置成功");
        Navigator.pop(context); //退出dialog
        Navigator.pop(context); //退出此页面
        Navigator.pop(context); //退出输入验证码页面
        //Navigator.pop(context); //退出输入手机号页面

        return;
      }

      if (entity.code == Api.ERROR_CODE || entity.code == Api.ERROR_CODE_0) {
        Navigator.pop(context);
        ToastUtil.showShortErrToast(entity.message);
        return;
      }
      Navigator.pop(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
    },
        //错误回调
        (error) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      Navigator.pop(context);
    });
  }

  Future _setPwd() async {
    FormData params = FormData.from({"newPwd": _t1Controller.text});
    DioManager.getInstance().post(Api.SETPWD, params, (json) {
      print("设置密码:$json");
      SetPwdEntity entity = SetPwdEntity.fromJson(json);
      if (entity.code == Api.SUCCESS_CODE) {
        if (entity.data.isInvite == 1) {
          //填写邀请人页面
          NavigatorUtils.push(context, Routes.inputInvitationCode,
              replace: true);
        } else {
          ToastUtil.showShortToast("设置成功");
          Navigator.pop(context); //退出dialog
          Navigator.pop(context); //退出此页面
          Navigator.pop(context); //退出输入验证码页面
          Navigator.pop(context); //退出输入手机号页面

        }

        return;
      }

      if (entity.code == Api.ERROR_CODE || entity.code == Api.ERROR_CODE_0) {
        Navigator.pop(context);
        ToastUtil.showShortErrToast(entity.message);
        return;
      }
      Navigator.pop(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
    },
        //错误回调
        (error) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      Navigator.pop(context);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _t1Controller.dispose();
    _t1Controller.dispose();
  }

  bool checkPwd() {
    String p1 = _t1Controller.text;
    String p2 = _t2Controller.text;

    if (p1.isEmpty) {
      ToastUtil.showShortErrToast("请输入密码");
      return false;
    }
    if (p1.length < 6) {
      ToastUtil.showShortErrToast("密码长度不低于6位");
      return false;
    }
    if (p1.length > 20) {
      ToastUtil.showShortErrToast("密码长度不高于20位");
      return false;
    }

    if (p1 != p2) {
      ToastUtil.showShortErrToast("两次输入的密码一致");
      return false;
    }

    return true;
  }
}
